// pages/play/play.js
const innerAudioContext = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state:"play",
    songid:'',
    songs:[],
    arraysongs:[],
    songlyrics:[],
    marinTop:0,
    index:0,
    playtime:"00:00",
    alltime:0,
    endtime:"00:00",
    //当前进度条的值
    movetime:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    var arr = options.songs;
    arr = JSON.parse(arr);
    this.setData({
      songid:id,
      songs:arr,
      arraysongs:arr,
    })

    //播放路径
    // onTimeUpdate才可以生效
    //innerAudioContext.autoplay = true
    innerAudioContext.src = "https://music.163.com/song/media/outer/url?id="+id;

    // play播放 pause停止
    innerAudioContext.pause();
    innerAudioContext.play();

    //获取歌词
    this.getLyricbyid(id);
    //获取歌词详细信息
    this.getMusicInfoById(id);

    //监听事件
    innerAudioContext.onCanplay(() => {
      var duration = innerAudioContext.duration;
      console.log("播放总时长:"+duration);
    })
    
    innerAudioContext.onPlay(() => {
      console.log('开始播放');
    })

    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

    var  that = this;
    //实时获取歌曲信息
    innerAudioContext.onTimeUpdate(() =>
    {
      var currenttime = innerAudioContext.currentTime;
      var duration = innerAudioContext.duration;

      if((currenttime+0.3) >= duration)
      {
        that.nextfunc();
      }

      // setTimeout(function(){
      //   var value=that.data.marinTop + 1;
      //   that.setData({
      //     marinTop:value
      //   })
      // },1500)
      //歌词滚动
      that.lyricscroll(currenttime,duration);
    })

    // this.setData({
    //   audio:innerAudioContext,
    // })
  },

  /** 
   * 歌词滚动
  */
  lyricscroll:function(currenttime,duration)
  {
    var playminute = Math.floor(currenttime/60);
    var playsecond = Math.floor(currenttime%60);

    var endminute = Math.floor(duration/60);
    var endsecond = Math.floor(duration%60);

    playminute = playminute<10?"0"+playminute:playminute;
    playsecond = playsecond<10?"0"+playsecond:playsecond;

    endminute = endminute<10?"0"+endminute:endminute;
    endsecond = endsecond<10?"0"+endsecond:endsecond;

    this.setData({
      playtime:playminute+":"+playsecond,
      endtime:endminute+":"+endsecond,
      duration:duration,
      movetime:currenttime,
    })

    var lyricArr = this.data.songlyrics;
    if(lyricArr != null)
    {
      //currenttime大于起始时间小于终止时间
      if(this.data.index == lyricArr.length-2)
      {
        if(currenttime>lyricArr[lyricArr.length-1][0])
        {
          this.setData({
            index:lyricArr.length-1,
          })
        }
      }
      else
      {
        for(var i=0;i<lyricArr.length-1;i++)
        {
          //judge歌词是否最后一句
          if(currenttime>=lyricArr[i][0] && currenttime<lyricArr[i+1][0])
          {
            this.setData({
              index:i,
            })
          }
        }
      }

      //歌词过几句开始滚动
      if(this.data.index>=3)
      {
        this.setData({
          marinTop:(this.data.index-3)*40,
        })
      }
      else
      {
        this.setData({
          marinTop:0,
        })
      }
    }
  },

  //歌词
  getLyricbyid:function(id)
  {
    var that = this;
    wx.request({
      url: 'https://music.163.com/api/song/lyric?os=pc&id='+id+'&lv=-1&kv=-1&tv=-1',

      success:function(res)
      {
        if(res.data.lrc.lyric != null)
        {
          var result = res.data.lrc.lyric;
           
            //解析歌词
            var newresult = that.explainlyric(result);
            //去除歌词为空
            var lyricresult = that.sliceNull(newresult);
            that.setData({
              songlyrics:lyricresult,
            })
        }
      }
    })
  },

  /** 
   * 去除空歌词
  */
 sliceNull:function(lyricarr){
  var result = [];
  for(var i=0;i<lyricarr.length;i++)
  {
    if(lyricarr[i][1] != "")
    {
      result.push(lyricarr[i]);
    }
  }
  return result;
 },

  /**
   * 解析歌词
   */
  explainlyric:function(lyric)
  {
    var lyricarr = lyric.split('\n');
    if(lyricarr[lyricarr.length-1] == "")
    {
      //删除空白
      lyricarr.pop();
    }

    var reg = /\[\d{2}:\d{2}\.\d{2,3}\]/;
    var finallyric = [];

    lyricarr.forEach(function(v,i,arr){
      var temp = v.replace(reg,"");
      var time = v.match(reg)[0];
      time = time.substring(1,time.length-1);

      var time = parseFloat(time.split(":")[0])*60+parseFloat(time.split(":")[1]);

      finallyric.push([time,temp]);
    })

    return finallyric;
    

    // this.setData({
    //   songlyrics:finallyric,
    // })
  },

   //根据歌曲的id获取歌曲详情的方法

   getMusicInfoById:function(id)
   {
    var that = this;
    wx.request({
      url: "https://music.163.com/api/song/detail/?id="+id+"&ids=["+id+"]",
      success:function(res){
         //输出歌曲的详情信息
         that.setData({
          songs:res.data.songs[0],
         })
      }
    })
   },

  /**
   * 拖动进度条
   */

  dragSilser:function(e)
  {
    var v = e.detail.value;
    innerAudioContext.seek(v);
  },

  /**
   * 暂停和播放功能实现
   */
  pauseORplay:function()
  {
    var state = this.data.state;
    if(state == 'play')
    {
      innerAudioContext.pause();
      this.setData({
        state:'pause',
      })
    }

    else
    {
        innerAudioContext.play();
        this.setData({
          state:'play',
        })
    }
  },

  /**
   * 上一首
   */
  prevfunc:function()
  {
    var songarray = this.data.arraysongs;
    var currentindex = 0;
    for(var i=0;i<songarray.length;i++)
    {
      if(songarray[i].id == this.data.songid)
      {
        currentindex = i;
      }
    }

    if(currentindex != 0)
    {
      this.setData({
        songid:songarray[currentindex-1].id,
      })
    }

    innerAudioContext.stop();
    innerAudioContext.src = "https://music.163.com/song/media/outer/url?id="+this.data.songid;
    innerAudioContext.play();

     //获取歌词
     this.getLyricbyid(this.data.songid);
     //获取歌词详细信息
     this.getMusicInfoById(this.data.songid);
  },

  /**
   * 下一首
   */
  nextfunc:function()
  {
    var songarray = this.data.arraysongs;
    var currentindex = 0;
    for(var i=0;i<songarray.length;i++)
    {
      if(songarray[i].id == this.data.songid)
      {
        currentindex = i;
      }
    }

    if(currentindex != songarray.length-1)
    {
      this.setData({
        songid:songarray[currentindex+1].id,
      })
    }

    innerAudioContext.stop();
    innerAudioContext.src = "https://music.163.com/song/media/outer/url?id="+this.data.songid;
    innerAudioContext.play();

     //获取歌词
     this.getLyricbyid(this.data.songid);
     //获取歌词详细信息
     this.getMusicInfoById(this.data.songid);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //退出停止播放音乐
    innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})